package com.hn.filter;

import com.alibaba.fastjson.JSONObject;
import com.hn.pojo.Result;
import com.hn.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.logging.LogRecord;
@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //如果是登录就要放行
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        HttpServletResponse res= (HttpServletResponse) servletResponse;
        String url = req.getRequestURL().toString();
        if(url.contains("login")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //先检验有没有jwt
        String jwt = req.getHeader("token");
        log.info("拦截到jwt："+jwt);
        if(jwt == null){
            Result notLogin = Result.error("NOT_LOGIN");
            String s = JSONObject.toJSONString(notLogin);
            res.getWriter().write(s);
            return;
        }
        //否则检验jwt
        try {
            JwtUtils.parseJWT(jwt);//解析失败会出异常
        }catch (Exception e){
            //如果没有全局异常处理器，则在添加重复信息回执行到这里
            Result notLogin = Result.error("NOT_LOGIN");
            String s = JSONObject.toJSONString(notLogin);
            res.getWriter().write(s);
            return;
        }
        log.info("令牌合法, 放行");
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
